import router from '@/router'
import { getToken } from '@/utils/auth'
import NProgress from 'nprogress'
import { isRelogin } from '@/utils/request'
import store from './store'
import { Message } from 'element-ui'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login']

router.beforeEach(((to, from, next) => {
  NProgress.start()
  if(getToken()){
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    if (to.path === '/login'){
      next({path:'/'})
      NProgress.done()
    }else if (whiteList.indexOf(to.path) !== -1) {
      next()
    }else{
      if(store.getters.roles.length === 0){
        isRelogin.show = true
        store.dispatch('GetInfo').then(() =>{
          isRelogin.show = false
          store.dispatch('GenerateRoutes').then(accessRoutes => {
            // 根据roles权限生成可访问的路由表
            router.addRoutes(accessRoutes) // 动态添加可访问路由表
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
          })
        }).catch(error => {
          store.dispatch('LogOut').then(() => {
            Message.error(error)
            next({ path: '/' })
          })
        })
        next()
      }else{
        next()
      }
    }
  }else{
    if (whiteList.indexOf(to.path) !== -1){
      next()
    }else{
      next(`/login?redirect=${to.fullPath}`)
    }
  }
}))
